package com.ciko.code.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ciko.code.adapter.MyFieldWorkAdapter;
import com.ciko.code.base.BaseListFragment;
import com.ciko.code.bean.MyFieldWorkBean;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.HttpClient;
import com.ciko.code.http.HttpResponseListener;
import com.ciko.code.http.Req.GetMyFieldWorkReq;
import com.ciko.code.http.Req.GetMyReceivedFieldWorkReq;
import com.ciko.code.views.LoadingView;
import com.ciko.code.views.pullrefresh.PullToRefreshBase;
import com.ciko.code.views.pullrefresh.PullToRefreshListView;
import com.mywork.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by LEECO on 2016/6/2.
 */
public class MyReceiveFieldWorkFragment extends Fragment  implements HttpResponseListener {

    private List<Object> myFieldWorkList;
    private List<Object> myFieldWorkList2;
    private PullToRefreshListView lVMyFieldWork;

    private final int LENGTH = 10;
    private final  int isFresh = 0;//0代表刷新，
    private final  int isLoad  = 1;//1代表加载
    private int refreshLoadTag = -1;//刷新还是加载的标志
    private ProgressDialog progressDialog;

    private MyFieldWorkAdapter myFieldWorkAdapter;
    private LoadingView loadingView;
    private ImageView ivEmptyIcon;
    private TextView tvEmptyConetxt,empty;
    private TextView                tvEmptyButon;
    private String title;
    private View view;
    private boolean hasMore = false;


    public MyReceiveFieldWorkFragment(String title){
        this.title = title;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_myfieldwork,null);
        initView();
        return view;
    }

    private void initView() {
        progressDialog = new ProgressDialog(getActivity());
        myFieldWorkList2 = new ArrayList<>();
        lVMyFieldWork = (PullToRefreshListView) view.findViewById(R.id.lVMyFieldWork);
        empty = (TextView) view.findViewById(R.id.empty);

        lVMyFieldWork.setPullLoadEnabled(true);
        lVMyFieldWork.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        lVMyFieldWork.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                refresh();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadMore();
            }
        });
    }
    @Override
    public void onStart() {
        super.onStart();
        doHttpRequst(System.currentTimeMillis(),LENGTH);
    }
    @Override
    public void onRequestStart(String tag) {
                progressDialog.setMessage("加载中...");
                progressDialog.setCancelable(true);
                progressDialog.show();
    }

    @Override
    public void onResponseSuccess(BaseResponse<?> response, String tag) {
               if (progressDialog.isShowing()){
                   progressDialog.dismiss();
           }

        lVMyFieldWork.onPullUpRefreshComplete();
        lVMyFieldWork.onPullDownRefreshComplete();

        List<MyFieldWorkBean> myFieldWorkBeanList = (List<MyFieldWorkBean>) response.getReturnObject();
        if (refreshLoadTag==-1&&myFieldWorkBeanList.size()==0){
            lVMyFieldWork.getRefreshableView().setEmptyView(empty);
            return;
        }
        //根据时间戳进行排序
        Collections.sort(myFieldWorkBeanList);
        //没有更多数据
        if (myFieldWorkBeanList.size()<10){
            lVMyFieldWork.setHasMoreData(false);
            hasMore = false;
        }else{
            hasMore = true;
        }
        //***********************************封装作为adapter的数据************************************
        myFieldWorkList = new ArrayList<>();
        if (myFieldWorkList2.size()==0) {
            myFieldWorkList.add(convertDate(myFieldWorkBeanList.get(0).getCreateTime()).split(" ")[0]);
        }else if(myFieldWorkList2.size()!=0&&refreshLoadTag==isLoad){
            String t1 = (convertDate(((MyFieldWorkBean)(myFieldWorkList2.get(myFieldWorkList2.size()-1))).getCreateTime())).split(" ")[0];
            String t2 = (convertDate(myFieldWorkBeanList.get(0).getCreateTime())).split(" ")[0];
            if(!t1.equals(t2)){
                myFieldWorkList.add(convertDate(myFieldWorkBeanList.get(0).getCreateTime()).split(" ")[0]);
            }
        }else if(myFieldWorkList2.size()!=0&&refreshLoadTag==isFresh){
            myFieldWorkList.add(convertDate(myFieldWorkBeanList.get(0).getCreateTime()).split(" ")[0]);
        }
        for (int i=0;i<myFieldWorkBeanList.size()-1;i++){
            Date date1 = new Date(myFieldWorkBeanList.get(i).getCreateTime());
            Date date2 = new Date(myFieldWorkBeanList.get(i+1).getCreateTime());
            if (isTheSameDate(date1,date2)){
                myFieldWorkList.add(myFieldWorkBeanList.get(i));
            }else{
                myFieldWorkList.add(myFieldWorkBeanList.get(i));
                myFieldWorkList.add(convertDate(myFieldWorkBeanList.get(i+1).getCreateTime()).split(" ")[0]);
            }
            if (i==myFieldWorkBeanList.size()-2){
                myFieldWorkList.add(myFieldWorkBeanList.get(i+1));
            }
        }
//        Log.e("封装后的数据：",myFieldWorkList.size()+"----------"+myFieldWorkList.toString());
        //***********************************封装结束************************************************
        if(refreshLoadTag==isLoad){
            myFieldWorkList2.addAll(myFieldWorkList);
            myFieldWorkAdapter.notifyDataSetChanged();
        }else {
            myFieldWorkList2.clear();
            myFieldWorkList2.addAll(myFieldWorkList);
            myFieldWorkAdapter = new MyFieldWorkAdapter(getActivity(), myFieldWorkList2,2);
            lVMyFieldWork.getRefreshableView().setAdapter(myFieldWorkAdapter);
        }
    }

    @Override
    public void onResponseFail(String tag, int resultCode) {
                if (progressDialog.isShowing()){
                    progressDialog.dismiss();
                    Toast.makeText(getActivity(),"加载失败，请稍后重试",Toast.LENGTH_SHORT).show();
                }
    }

    private void loadMore(){
        refreshLoadTag = 1;
        if (hasMore) {
            doHttpRequst(((MyFieldWorkBean) (myFieldWorkList.get(myFieldWorkList.size() - 1))).getCreateTime(), LENGTH);
        }else{
            lVMyFieldWork.onPullDownRefreshComplete();
            lVMyFieldWork.onPullUpRefreshComplete();
        }
    }

    private void refresh(){
        refreshLoadTag = 0;
        doHttpRequst(0,LENGTH);
    }
    private void doHttpRequst(long lastCreateTime, int length) {
        HttpClient.getInstance(getActivity()).post(new GetMyReceivedFieldWorkReq(lastCreateTime,length), this);
    }


    public String convertDate(long timeT){
        SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String date = df3.format(new Date( timeT));
        return date ;
    }

    //判断两个时间戳(Timestamp)是否在同一天
    public static boolean isTheSameDate(Date time1, Date time2 )
    {
        if(time1!=null&&time2!=null){
            Calendar c1=Calendar.getInstance();
            c1.setTime(time1);
            int y1=c1.get(Calendar.YEAR);
            int m1=c1.get(Calendar.MONTH);
            int d1=c1.get(Calendar.DATE);
            Calendar c2=Calendar.getInstance();
            c2.setTime(time2);
            int y2=c2.get(Calendar.YEAR);
            int m2=c2.get(Calendar.MONTH);
            int d2=c2.get(Calendar.DATE);
            if(y1==y2&&m1==m2&&d1==d2) {
                return true;
            }
        }
        else {
            if(time1==null&&time2==null) {
                return true;
            }
        }
        return false;
    }
}
